package user

import (
	"api-go/cache"
	"api-go/model"
	"api-go/serializer"
	"fmt"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/upyun/go-sdk/v3/upyun"
)

// 用户注册所需信息
type UserRegisterService struct {
	Username        string `form:"username" binding:"required,min=3,max=18"`
	Password        string `form:"password" binding:"required,min=6,max=18"`
	PasswordConfirm string `form:"password_confirm" binding:"required,min=6,max=18"`
	Email           string `form:"email" binding:"email"`
	DeviceId        string `form:"device_id"`
	Avatar          string `form:"avatar"`
	Role            string `form:"role"`
	State           int8   `form:"state"`
	Nickname        string `form:"nickname"`
}

// 验证表单
func (service *UserRegisterService) Valid() *serializer.Response {

	// 两次输入密码不一致
	if service.PasswordConfirm != service.Password {
		return serializer.ErrorResponse(serializer.CodePasswordConfirmError)
	}

	// 用户名已存在
	res := model.DB.Where("username = ?", service.Username).First(&model.User{})
	if res.RowsAffected > 0 {
		return serializer.ErrorResponse(serializer.CodeUserExistError)
	}

	// 用户名已存在(防止用户名用邮箱，且该邮箱已经存在)
	resss := model.DB.Where("username = ?", service.Email).First(&model.User{})
	if resss.RowsAffected > 0 {
		return serializer.ErrorResponse(serializer.CodeUserExistError)
	}

	// 邮箱已存在
	ress := model.DB.Where("email = ?", service.Email).First(&model.User{})
	if ress.RowsAffected > 0 {
		return serializer.ErrorResponse(serializer.CodeEmailExistError)
	}
	return nil
}

// 用户注册
func (service *UserRegisterService) Register(c *gin.Context) *serializer.Response {

	// 表单验证
	if err := service.Valid(); err != nil {
		return err
	}

	//未设置昵称，则默认为用户名
	if val := service.Nickname; val != "" {
		service.Nickname = val
	} else {
		service.Nickname = service.Username
	}

	//未设置头像
	if val := service.Avatar; val != "" {
		service.Avatar = val
	} else {
		service.Avatar = "http://qt.music.canace.cn/avatar.png"
	}

	user := model.User{
		Username: service.Username,
		Nickname: service.Nickname,
		Email:    service.Email,
		Avatar:   service.Avatar,
		Role:     "user",
		State:    1,
		DeviceId: service.DeviceId,
	}

	// 加密密码
	if err := user.SetPassword(service.Password); err != nil {
		return serializer.ErrorResponse(serializer.CodeUnknownError)
	}

	// 创建用户
	if err := model.DB.Create(&user).Error; err != nil {
		return serializer.ErrorResponse(serializer.CodeUnknownError)
	}

	// 响应信息
	data := serializer.BuildUserResponse(&user)
	return serializer.OkResponse(data)
}

//文件上传
func FileUpload(c *gin.Context) *serializer.Response {
	avatarUrl := "http://qt.music.canace.cn"

	var avatarArr string
	avatar, file, err := c.Request.FormFile("avatar")
	if err != nil {
		fmt.Println(err)
	}

	//文件大小小于1M
	if file.Size < 1048576 {
		//将文件名和时间戳结合，防止文件名一样冲突
		// fileNameWithSuffix := filepath.Base(service.Avatar)
		filename := strconv.FormatInt(time.Now().UnixNano(), 10) + file.Filename
		e := cache.Up.Put(&upyun.PutObjectConfig{
			Path: "/avatar/" + filename,
			// LocalPath: service.Avatar,
			Reader: avatar,
		})
		//表示文件上传成功
		if e == nil {
			avatarArr = avatarUrl + "/avatar/" + filename
		} else {
			fmt.Println(e)
			return serializer.ErrorResponse(serializer.CodeUploadErrot)
		}
		result := gin.H{
			"data": avatarArr,
		}
		return serializer.OkResponse(result)
	} else {
		return serializer.ErrorResponse(serializer.CodeUploadErrot)
	}

}
